Go での test の書き方
coverage
package 單位
$ go test -v -cover -race ./...
詳細に
$ go test -v -coverprofile=./coverage.txt -race ./...
$ go tool cover -html coverage.txt
たくさんの test case を書く時
(*testing.T).Run() を使ふ
code:1_test.go
import "testing"
func Test_Example(t *testing.T) {
t.Run("こんな test だよ", func (t *testing.T) {
t.Fatal("停め放題")
})
}
map で test case を竝べる
code:2_test.go
import "testing"
func Test_Example(t *testing.T) {
expected: int
} := {
"こんな test だよ": {
expected: 42,
},
}
for title, tt := range tests {
t.Run(title, func (t *testing.T) {
t.Fatalf("%d だけど停め放題", t.expected)
})
}
}
差分
reflect.DeepEqual() の上位互換だょ
code:go
import (
"testing"
"github.com/google/go-cmp/cmp"
)
func Test_Example(t *testing.T) {
// 云々
if diff := cmp.Diff(want, got); diff != "" {
t.Error(diff)
}
}
mock
code:3.go
type IExample interface {
Example(a int) (bool, error)
}
type R struct {
Example IExample
}
func (r *R) Sample() { }
code:3_test.go
import "testing"
type exampleImpl struct { }
func (e exampleImpl) Example(a int) (bool, error) { }
func Test_Example(t *testing.T) {
r := R{ Example: exampleImpl { } }
r.Sample()
}
code:3_test.go
import (
"testing"
"github.com/stretchr/testify/mock"
)
type example struct {
mock.Mock
}
func (e *example) Example(a int) (bool, error) {
ret := e.Called(a)
return ret.Bool(0).(bool), ret.Error(1)
}
func Test_Example(t *testing.T) {
e := new(example)
m := e.On("Example", 42).Return(true, nil)
r := R{ Example: e }
r.Sample()
m.Unset()
}
mutex で函數實裝表を管理する泥臭い事をやってくれてる